using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CommonUtils;

namespace ShellAnywhere.Model
{
	public class Shell : Target
	{
		#region ctors
		public Shell(string targetPath, string name = null) : base(targetPath, name) { }
		public Shell(string targetPath, string arguments, string name = null) : base(targetPath, arguments, name) { }
		public Shell(string targetPath, string arguments, string description, string name = null) : base(targetPath, arguments, description) { }
		~Shell() { Stop(); }
		#endregion ctors

		#region props
		//public override ParamType ParamType { get { return ParamType.Shell; } }
		public Action<string> StdOut
		{
			get { return _AsyncProcess.StdOut; }
			set { _AsyncProcess.StdOut = value; }
		}
		public Action<string> StdErr
		{
			get { return _AsyncProcess.StdErr; }
			set { _AsyncProcess.StdErr = value; }
		}
		public StreamWriter StdIn
		{
			get { return _AsyncProcess.StdIn; }
		}
		#endregion props

		#region methods
		public void Start(Action<string> stdOut, Action<string> stdErr)
		{
			Stop();
			AsyncProcessStartInfo aspi = new AsyncProcessStartInfo(/*TargetPath*/Path, Arguments);
			aspi.StdOut = stdOut;
			aspi.StdErr = stdErr;
			aspi.WorkingDirectory = Common.Desktop;
			_AsyncProcess = AsyncProcess.Start(aspi);
		}
		public void Stop()
		{
			try
			{
				if (_AsyncProcess != null)
					_AsyncProcess.Kill();
			}
			catch { }
		}
		public void SendCommand(string text)
		{
			_AsyncProcess.StdIn.WriteLine(text);
			_AsyncProcess.StdIn.Flush();
		}
		//public override IParam Clone()
		//{
		//    Shell clone = new Shell(TargetPath, Arguments, Description);
		//    clone.Name = Name;
		//    clone.Dot = Dot;
		//    return clone;
		//}
		#endregion methods

		#region fields
		private AsyncProcess _AsyncProcess;
		#endregion fields
	}
}
